var iot = require('iot');
var network = require('network');
var player = require('audioplayer');
var linkspeech = require('./linkspeech.js');

const productkey = ''; //your productkey
const devicename = ''; //your devicename
const devicesecret = ''; //your devicesecret

var tonepathPowerOn = "/resource/poweron.wav";
var tonepathConnected = "/resource/connected.wav";

console.log('\r\n----------------------- linkspeech application demo -----------------------\r\n');

player.setVolume(3);

var networkClient = network.openNetWorkClient();

var iotdev;

function iotDeviceCreate()
{
  iotdev = iot.device({
    productKey: productkey,
    deviceName: devicename,
    deviceSecret: devicesecret,
    keepalive_interval: 30000,
    success: function() {
      console.log('success connect to aliyun iot server');
      player.play(tonepathConnected, function(){console.log('play ' + tonepathConnected + ' complete')});
    },
    fail: function() {
      console.log('fail to connect to aliyun iot server');
    }
  });

  iotdev.on('close', function() {
    console.log('iot close');
  });

  iotdev.on('error', function(data) {
    console.log('error ' + data);
  });

  iotdev.on('props', function(request_len, request) {
    console.log('received cloud request len is ' + request_len);
    console.log('received cloud request is ' + request);
  });

  iotdev.on('service', function(serviceid, request) {
    linkspeech.process(0, iotdev, serviceid, request);
  });

  iotdev.on('syncservice', function(serviceid, request) {
    linkspeech.process(1, iotdev, serviceid, request);
  });
}

player.play(tonepathPowerOn, function() {
  var netStatus = networkClient.getStatus();
  if (netStatus == 'connect') {
    iotDeviceCreate();
  } else {
    networkClient.on('connect', function() {
      iotDeviceCreate();
    });
  }
})